from pathlib import Path
from uuid import uuid4
from io import BytesIO
import subprocess
from PIL import Image
from .base import ToolError

OUTPUT_DIR = "./tmp/outputs"

def get_android_screenshot(resize: bool = False, target_width: int = 1080, target_height: int = 1920):
    """Capture Android screenshot using ADB and perform basic processing."""
    output_dir = Path(OUTPUT_DIR)
    output_dir.mkdir(parents=True, exist_ok=True)
    path = output_dir / f"screenshot_{uuid4().hex}.png"
    
    try:
        # Capture screenshot using ADB
        process = subprocess.Popen(
            ['adb', 'exec-out', 'screencap', '-p'],
            stdout=subprocess.PIPE
        )
        screenshot_data, _ = process.communicate()
        
        if process.returncode != 0:
            raise ToolError("Failed to capture screenshot via ADB")
        
        image = Image.open(BytesIO(screenshot_data))
        
        # Resize if needed
        if resize and image.size != (target_width, target_height):
            image = image.resize((target_width, target_height))
        
        # Save and return
        image.save(path)
        return image, path
        
    except Exception as e:
        raise ToolError(f"Android screenshot capture failed: {str(e)}")